package com.rowline.admin.module.util.context;

import lombok.Getter;
import lombok.Setter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * ClassName:RequestContext
 * Created by 245167
 * on 2017/8/10  10:02
 * description:
 */
public class RequestContext {

    private static ThreadLocal<RequestContext> context = new ThreadLocal<RequestContext>() {
        @Override
        protected RequestContext initialValue(){
            return new RequestContext();
        }
    };

    @Setter @Getter
    private HttpServletRequest httpRequest ;

    @Setter @Getter
    private HttpServletResponse httpResponse ;
    /**
     * 请求URL
     */
    @Setter @Getter
    private String url;
    /**
     * 请求id
     */
    @Setter @Getter
    private String requestId;
    /**
     * 请求ip
     */
    @Setter @Getter
    private String requestIp;

    /**
     * 请求Header
     */
    @Setter @Getter
    private String requestHeader;

    /**
     * method post/get
     */
    @Setter @Getter
    private String requestMethod;

    /**
     * 请求参数
     */
    @Setter @Getter
    private String requestParam;

    /**
     *
     * @Title: RequestContext
     * @Description: 单例 - 构造器
     * @throws
     */
    private RequestContext() {
        this.requestId = UUID.randomUUID().toString();
    }

    /**
     * 获取当前上下文对象
     * @return
     */
    public static RequestContext currentContext() {
        return context.get();
    }

    /**
     * 全局获取request
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        HttpServletRequest request = currentContext().getHttpRequest();
        if (null != request)
            return request;
        if(null != RequestContextHolder.getRequestAttributes()){
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            currentContext().setHttpRequest(request);
            return request;
        }
        return null;
    }

    /**
     * 清除ThreadLocal remove
     */
    public static void remove() {
        context.remove();
    }

}
